package nancal.mp.mvc.sys

import nancal.mp.db.mongo.mor
import nbcp.base.comm.JsonResult
import nbcp.base.comm.ListResult
import nbcp.base.comm.PagerModel
import nbcp.base.extend.HasValue
import nbcp.base.extend.must
import nbcp.myoql.db.db
import nbcp.myoql.db.mongo.deleteById
import nbcp.myoql.db.mongo.entity.SysAnnex
import nbcp.myoql.db.mongo.query
import nbcp.myoql.db.mongo.queryById
import nbcp.web.service.upload.MinioBaseService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class FileController {

    @PostMapping("/sys/file/list")
    fun list(group: String, corpId: Int, @org.springframework.web.bind.annotation.RequestBody query:PagerModel<Any?>): ListResult<SysAnnex> {
        return mor.base.sysAnnex.query()
            .apply {
                if (group.HasValue) {
                    this.where { it.group mongoEquals group }
                }

                if (corpId.HasValue) {
                    this.where { it.corpId mongoEquals corpId }
                }
            }
            .orderByDesc { it.id }
            .withPager(query)
            .toListResult()
    }

    @Autowired
    lateinit var minioService: MinioBaseService;

    @RequestMapping("/sys/file/delete/{id}")
    fun delete(id: String): JsonResult {
        var file = mor.base.sysAnnex.queryById(id).toEntity().must().elseThrow { "找不到附件" }
        mor.base.sysAnnex.deleteById(id).exec();
        if (db.affectRowCount == 0) {
            return JsonResult.error("删除失败")
        }
        return minioService.delete(file.url);
    }
}